package com.beta.cust.bind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beta.cust.bind.builder.CustBuilder;
import com.beta.cust.bind.constant.BusinessConstant;
import com.beta.cust.bind.mapper.CrmCustDetailMapper;
import com.beta.cust.bind.mapper.entity.CrmCustDetail;
import com.beta.cust.bind.mapper.entity.EmpCustRef;
import com.beta.cust.bind.service.ICrmCustDetailService;
import com.beta.cust.bind.service.ICustInfoService;
import com.beta.cust.bind.service.IEmpCustRefService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 客户(CRM)信息表 服务实现类
 * </p>
 *
 * @author pcc
 * @since 2024-03-12
 */
@Service
public class CrmCustDetailServiceImpl extends ServiceImpl<CrmCustDetailMapper, CrmCustDetail> implements ICrmCustDetailService {

    @Autowired
    private IEmpCustRefService empCustRefService;

    @Autowired
    private ICrmCustDetailService crmCustDetailService;

    @Autowired
    private ICustInfoService custInfoService;

    @Override
    public void deleteByPhone(String custPhone, String managerPhone) {
        CrmCustDetail update = new CrmCustDetail();
        update.setDelFlag(BusinessConstant.IS_DEL_FLAG);
        this.baseMapper.update(update,new LambdaQueryWrapper<CrmCustDetail>()
                .eq(CrmCustDetail::getDelFlag,BusinessConstant.IS_NOT_DEL_FLAG)
                .eq(CrmCustDetail::getCustManagerPhone, managerPhone)
                .eq(CrmCustDetail::getPhone, custPhone));
    }

    /**
     * 事务分开分装，避免锁已释放事务未提交
     * @param crmCustDetail
     * @param custRef
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealCustRel(CrmCustDetail crmCustDetail, EmpCustRef custRef) {
        empCustRefService.updateById(custRef);
        crmCustDetailService.deleteByPhone(crmCustDetail.getPhone(), crmCustDetail.getCustManagerPhone());
        crmCustDetailService.save(crmCustDetail);
        custInfoService.updateByExternal(custRef.getExternalUserid(), CustBuilder.buildUpdateCustInfo(crmCustDetail.getCrmCustId()),custRef.getCorpId());
    }
}
